package cn.com.dhcc.turbo.service.registry.sync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.NetUtil;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.app.pub.core.util.FtpUtil;
import cn.com.dhcc.turbo.entity.registry.AdapterBase;
import cn.com.dhcc.turbo.entity.registry.DataCategory;
import cn.com.dhcc.turbo.entity.registry.DomainInfo;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncOperType;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncStatus;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.service.registry.AdapterBaseService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.DataCategoryService;
import cn.com.dhcc.turbo.service.registry.DomainInfoService;


/**
 * 打包内网信息  向网闸同步
 * 
 * @日期 2015-4-22 上午11:27:34
 * @作者  高强
 */
@Service(AppIocBean.SYNCHRONIZE_TO_GAP_BEAN)
public class SynchronizeToGapServiceImpl implements ISynchronizeToGapService{
	private Logger log = Log.getLogger(LOGTYPE.SYNC);
	@Autowired
	BaseInfoService baseInfoService;
	@Autowired
	AdapterBaseService adapterBaseService;
	
	@Autowired
	DataCategoryService dataCategoryService;
	
	@Autowired
	DomainInfoService domainInfoService;
	@Override
	public void sendToGap(List<?> list,SyncType type, String ip, int port,String home,String username,String password) throws ServiceException {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put(ISynchronizeToGapService.SYNCTYPE, type.getCode());//类型
		map.put(ISynchronizeToGapService.SYNCDATA, list);//数据
		String path =AppConst.APP_GAP_FTP_OUT_LOCALFTPPUT;//获取临时生成的文件的目录
		NodeInfo localNode=baseInfoService.getCurrentNodeInfo();
		File jsonFile=new File(path,localNode.getNodeCode()+"_"+UUIDGenerator.getUUID()+ISynchronizeToGapService.SUFFIX);
		JsonUtil.toJsonFile(jsonFile, map);
		Status status = FtpUtil.upload(new FTPClient(),ip,
				username,
				password,
				port, jsonFile,
				home+File.separator + jsonFile.getName());
		
		SynchronizeInfo synchronizeInfo=new SynchronizeInfo();
		synchronizeInfo.setId(UUIDGenerator.getUUID());
		synchronizeInfo.setFromNode(localNode.getId());
		synchronizeInfo.setDataContent(JsonUtil.toJson(map));
		synchronizeInfo.setFromNodeName(localNode.getNodeName());
		synchronizeInfo.setSrcNode(localNode.getId());
		synchronizeInfo.setFromNodeInfo(localNode);
		synchronizeInfo.setSrcNodeInfo(localNode);
		synchronizeInfo.setToNodeInfo(null);
		synchronizeInfo.setWhenErrorRepeat(false);
		synchronizeInfo.setOperType(SyncOperType.UPDATE.getCode());
		synchronizeInfo.setDataType(type.getCode());
		if (status.isSuccess()) {
			synchronizeInfo.setStatus(SyncStatus.SUCCESS.getCode());
		}else{
			synchronizeInfo.setStatus(SyncStatus.FAIL.getCode());
			synchronizeInfo.setRemark("信息发送到网闸失败："+status.getMsg());
			log.error("同步信息发送到网闸失败"+status.getMsg());
		}
		synchronizeInfo.setToNode(localNode.getId());
		synchronizeInfo.setToNodeName("网闸");
		synchronizeInfo.setSn(UUIDGenerator.getUUID());
		synchronizeInfo.setMtime(new Date());
		synchronizeInfo.setSyncUrl(null);
		try {
			CM.getDao().saveOrUpdateModuleById("", synchronizeInfo, null);
		} catch (DaoException e) {
			log.error("同步信息发送到网闸失败"+e);
			throw new ServiceException("更新synchronizeInfo失败");
		}
	}

	/**
	 * 从网闸解析文件
	 * @param ip
	 * @param port
	 * @param home
	 * @param username
	 * @param passwrod
	 * @throws ServiceException
	 */
	@SuppressWarnings("unchecked")
	public void analyzeFromGap(String ip, int port,String home,String username,String password) throws ServiceException {
		FTPClient ftpClient = new FTPClient();
		ftpClient.setConnectTimeout(AppConst.FTP_TIMEOUT);
		ftpClient.setDefaultTimeout(20000);
		ftpClient.setDataTimeout(20000);      //设置数据超时   10秒
		ftpClient.setControlEncoding("utf-8");
		if(!NetUtil.canConnect(ip, port))return;//尝试连接
		FileOutputStream fos = null;
		try {
			NodeInfo localNode=baseInfoService.getCurrentNodeInfo();
			ftpClient.connect(ip, port);
			ftpClient.login(username, password);
			
			if (home!=null && !"".equals(home)) {
				ftpClient.changeWorkingDirectory(home);
			}
			
			File temp=new File(AppConst.APP_GAP_FTP_INNER_LOCALFTPPUT);//创建临时目录
			if (!temp.exists()) {
				temp.mkdirs();
			}
			
			FTPFile[] files = ftpClient.listFiles();
			String fileName=null;
			File localFile=null;
			for (FTPFile file : files) {
			  if (file.isFile() && file.getName().endsWith(ISynchronizeToGapService.SUFFIX)) {
				  fileName = file.getName();
				if (!fileName.substring(0, 6).equals(localNode.getNodeCode().substring(0, 6))) {
					continue;
				}
				localFile = new File(temp ,fileName);
				fos = new FileOutputStream(localFile);
				
				ftpClient.setBufferSize(1024*1024*10);
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				ftpClient.enterLocalPassiveMode();
				ftpClient.retrieveFile(fileName, fos);
				ftpClient.enterLocalPassiveMode();
				fos.flush();
				
				String str=FileUtils.readFileToString(localFile,"UTF-8");
				Map<String,Object> map=JsonUtil.toMap(str);
				if (map!=null && !map.isEmpty()) {
					if (map.get(ISynchronizeToGapService.SYNCTYPE).equals(SyncType.DOMAIN_INFO.getCode())) {
						List<DomainInfo> list=JsonUtil.toObjectList(JsonUtil.toJson(map.get(ISynchronizeToGapService.SYNCDATA)), DomainInfo.class);
						//更新或添加
						for (DomainInfo domainInfo : list) {
							DomainInfo vo=domainInfoService.get(domainInfo.getId());
							if (vo==null) {
								domainInfoService.addAndSync(domainInfo);
							}else{
								domainInfoService.updateAndSyncDomain(domainInfo);
							}
							
						}
					}else if (map.get(ISynchronizeToGapService.SYNCTYPE).equals(SyncType.ADAPTER_BASE.getCode())) {
						List<AdapterBase> list=JsonUtil.toObjectList(JsonUtil.toJson(map.get(ISynchronizeToGapService.SYNCDATA)), AdapterBase.class);
						//更新或添加
						for (AdapterBase adapterBase : list) {
							AdapterBase vo=adapterBaseService.get(adapterBase.getId());
							if (vo==null) {
								adapterBaseService.insertAdapterBaseAndSync(adapterBase);
							}else{
								adapterBaseService.updateAdapterBaseAndSync(adapterBase);
							}
							
						}
					}else if (map.get(ISynchronizeToGapService.SYNCTYPE).equals(SyncType.DATACATEGORY.getCode())) {
						List<DataCategory> list=JsonUtil.toObjectList(JsonUtil.toJson(map.get(ISynchronizeToGapService.SYNCDATA)), DataCategory.class);
						//更新或添加
						for (DataCategory dataCategory : list) {
							DataCategory vo=dataCategoryService.get(dataCategory.getId());
							if (vo==null) {
								dataCategoryService.insertDataCategoryAndSync(dataCategory);
							}else{
								dataCategoryService.updateDataCategoryAndSync(dataCategory);
							}
							
						}
					}
				}
				
				localFile.delete();
				ftpClient.enterLocalPassiveMode();
				ftpClient.deleteFile(fileName);
			  }
			}
			
		} catch (Exception e) {
			log.error("从网闸解析同步数据文件异常"+e);
		}finally{
			if (fos!=null) {
				try {
					fos.close();
				} catch (IOException e) {
					log.error("从网闸解析同步数据文件异常"+e);
				}
			}
		}
		
		
		
		
	}

	
}
